package org.example.event;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

public class SpringEventTest implements Runnable {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Override
    public void run() {
        MyEventSource source = new MyEventSource("source1");
        eventPublisher.publishEvent(new MyApplicationEvent(source, 1));
        eventPublisher.publishEvent(new MyApplicationEvent(source, 2));
        eventPublisher.publishEvent(new MyApplicationEvent(source, "Hello, world"));
        eventPublisher.publishEvent(new MyApplicationEvent2(source, "async1"));
        eventPublisher.publishEvent(new MyApplicationEvent2(source, "async2"));
    }

    @Component
    @Slf4j
    static class MyApplicationListener {
        @EventListener(MyApplicationEvent.class)
        public void onEvent(MyApplicationEvent event) {
            log.info("on event: {}", event);
        }
    }

    @Component
    @Slf4j
    static class MyApplicationListener2 {
        @EventListener(MyApplicationEvent2.class)
        @Async
        public void onEvent(MyApplicationEvent2 event) {
            log.info("on event: {}", event);
        }
    }
}
